<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Authentication Library
 * 
 * @package     Personal
 * @category    Library
 * @author      Gene Bryan Ronquillo
 * @link        http://generonquillo.com
 * @version     2.0
 */

class Auth {
    
	public $ci = '';
	
    public function __construct()
    {
        $this->ci =& get_instance();
        
        $this->ci->load->model('auth_model');
    }
    
    // ------------------------------------------------------------------------
    
    public function login($fields)
    {
        $user = $this->ci->auth_model->login($fields);
        
        if ($user === FALSE) return FALSE;
        
        // update activity
        $this->ci->auth_model->update_last_activity($user['user_id']);
        
        // create cookie
        $this->create_cookie($user);
        return TRUE;
    }
    
    // ------------------------------------------------------------------------
    
    public function create_cookie($user = '')
    {
        $user = $user ? $user : $this->ci->auth_model->get_user();
        
        $data = array(
            'user_id'       => $user['user_id'],
            'key'           => $this->ci->auth_model->_hash_string($user['password'], $user['salt']),
            'logged_in'     => TRUE
        );
        
        $this->ci->session->set_userdata($data);
        
        return TRUE;
    }
    
    // ------------------------------------------------------------------------
    
    public function is_logged_in($user_type = '')
    {
        $user = $this->ci->auth_model->get_user();
        
        if ($user)
        {
            $key = $this->ci->auth_model->_hash_string($user['password'], $user['salt']);
            
            // check for validity
            if (($this->ci->session->userdata('logged_in') == TRUE) && ($this->ci->session->userdata('key') == $key))
            {
                $this->ci->auth_model->update_last_activity($user['user_id']);
                
                // return user or TRUE?
                return $user;
            }
        }
        
        // no user found
        $this->logout();
		redirect('login');
        //redirect($user_type != 'admin' ? 'login' : 'admin/login');
        // return FALSE;
    }
    
    // ------------------------------------------------------------------------
    
    public function logout()
    {
        $this->ci->session->sess_destroy();
        return TRUE;
    }
    
    // ------------------------------------------------------------------------
    
}

/* End of file auth.php */
/* Location: ./application/libraries/auth.php */